package com.qf.vote2203.producer;

import com.qf.vote2203.dbvote.entity.Vote;
import com.qf.vote2203.utils.Constants;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;

@Component
public class VoteInfoProducer {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Scheduled(cron = "0/5 * * * * ?")
    public void productMsg(){
        ArrayList<Vote> votes = new ArrayList<>();

        while (true){
            final Vote vote = (Vote) redisTemplate.opsForList().leftPop(Constants.VOTE_DETAIL_LIST);
            if (vote==null){
                if (votes.size()>0){
                    // 写入 mq
                    rabbitTemplate.convertAndSend("vote_exchage","vote.batch",votes);
                }
                System.out.println("============nothing to produce=========");
                return;
            }else if (vote!=null&&votes.size()<10){
                votes.add(vote);
            }else {
                // 写入 mq
                rabbitTemplate.convertAndSend("vote_exchage","vote.batch",votes);
                votes = new ArrayList<>();
            }
        }


    }

}
